// 56.合并区间
package LeetcodeHot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution056 {
    public int[][] merge(int[][] intervals) {
        // 根据第一个元素进行排序
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0];
            }
        });
        // 遍历数组进行区间组合
        List<int[]> list = new ArrayList<>();
        int start = intervals[0][0];
        int end = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] > end) {
                list.add(new int[] { start, end });
                start = intervals[i][0];
                end = intervals[i][1];
            } else {
                if (intervals[i][1] > end)
                    end = intervals[i][1];
            }
        }
        list.add(new int[] { start, end });
        return list.toArray(new int[list.size()][]);
    }

    public static void main(String[] args) {
        int[][] intervals = new int[][] { { 17, 3 }, { 21, 6 }, { 8, 10 }, { 15, 18 } };
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0];
            }
        });
        for (int[] intervals2 : intervals) {
            System.out.println(intervals2[0] + "@" + intervals2[1]);
        }
    }
}
